const consts = require('../../../util/consts');
const utils = require('../../../util/utils');
const pushUtils = require('../../../util/pushUtils');
const async = require('async');
const httpRequest = require('request');
const AsyncLock = require('async-lock');

module.exports = function (app) {
    return new Handler(app);
}

const Handler = function (app) {
    this.app = app;
    this.consts = consts;
    this.httpRequest = httpRequest;
};

const handler = Handler.prototype;

const {
    getUserMoneyAndOil
} = require('../../login/lib/dao');

const {
    getUserMachineCount
} = require('../lib/dao');

const lock = new AsyncLock({timeout: 1000});

/**
 * 获取用户的矿机信息
 * @param msg
 * @param session
 * @param next
 */
handler.c2sMachineInfo = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');
    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }

        self.httpRequest({
            url: 'http://39.98.74.164:9292/api/oil/machine/info?uid=' + uid,
            method: "GET"
        }, function (error, response, body) {
            if (error) {
                console.error('c2sMachineInfo error:' + error);
                next(null, {
                    code: self.consts.Code.ERR,
                    msg: self.consts.Msg.NET_WORK_BUSY
                });
                return;
            }
            if (response && response.statusCode != 200) {
                next(null, {
                    code: self.consts.Code.ERR,
                    msg: self.consts.Msg.NET_WORK_BUSY
                });
                return;
            } else {
                body = JSON.parse(body);
                if (body.code != '0') {
                    next(null, {
                        code: self.consts.Code.DATA_ERR,
                        msg: body.error
                    });
                    return;
                } else {
                    next(null, {
                        code: self.consts.Code.SUC,
                        msg: self.consts.Msg.RESULT_SUCCESS,
                        data: body.data
                    });
                    return;
                }
            }
        });
    });
}

/**
 * 获取矿机配置信息
 * @param msg
 * @param session
 * @param next
 */
handler.c2sMachineConfig = function (msg, session, next) {
    let self = this;
    next(null, {
        code: self.consts.Code.SUC,
        msg: self.consts.Msg.RESULT_SUCCESS,
        data: [
            {
                title: '灰木',
                name: '微型',
                price: 3000,
                product: 1,
                period: 30
            },
            {
                title: '黑铁',
                name: '小型',
                price: 10000,
                product: 2,
                period: 60
            },
            {
                title: '青铜',
                name: '中型',
                price: 32000,
                product: 4,
                period: 90
            },
            {
                title: '白银',
                name: '大型',
                price: 100000,
                product: 6,
                period: 180
            },
            {
                title: '黄金',
                name: '重型',
                price: 134000,
                product: 8,
                period: 180
            },
            {
                title: '砖石',
                name: '巨型',
                price: 168000,
                product: 10,
                period: 180
            }
        ]
    });
    return;
}

/**
 * 购买矿机
 * @param msg
 * @param session
 * @param next
 */
handler.c2sPurchaseMachine = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');
    var level = msg.level;

    //获取锁
    lock.acquire(consts.LockKey.MACHINE_LOCK + uid, async function () {
        let userInfo = await self.app.userRemote(uid, 'get', [uid, 'user']);
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        let cost = 600000;
        switch (level) {
            case 1:
                cost = 3000;
                break;
            case 2:
                cost = 10000;
                break;
            case 3:
                cost = 32000;
                break;
            case 4:
                cost = 100000;
                break;
            case 5:
                cost = 134000;
                break;
            case 6:
                cost = 168000;
                break;
        }
        let balanceObj = await getUserMoneyAndOil.call(self, uid);
        //石油不足
        if (balanceObj.oil < cost) {
            next(null, {
                code: self.consts.Code.DATA_ERR,
                msg: self.consts.Msg.OIL_INSUFFICIENT
            });
            return;
        }
        let count = await getUserMachineCount.call(self, uid, level);
        if (level == 1) {
            if (count >= 1) return next(null, {
                code: self.consts.Code.DATA_ERR,
                msg: '微型矿机只能购买1台'
            });
        } else if (level == 2) {
            if (count >= 2) return next(null, {
                code: self.consts.Code.DATA_ERR,
                msg: '小型矿机只能购买2台'
            });
        } else if (level == 3) {
            if (count >= 3) return next(null, {
                code: self.consts.Code.DATA_ERR,
                msg: '中型矿机只能购买2台'
            });
        }

        self.httpRequest({
            url: 'http://39.98.74.164:9292/api/oil/machine/init?uid=' + uid + '&level=' + level + '&is_try=' + false,
            method: "GET"
        }, function (error, response, body) {
            if (response.statusCode != 200) {
                console.error('c2sPurchaseMachine 执行失败 response.statusCOde' + response.statusCode)
                next(null, {
                    code: self.consts.Code.DATA_ERR,
                    msg: self.consts.Msg.NET_WORK_BUSY
                });
                return;
            } else {
                body = JSON.parse(body);
                if (body.code != '0') {
                    next(null, {
                        code: self.consts.Code.DATA_ERR,
                        msg: body.error
                    });
                    return;
                } else {
                    //操作石油
                    self.app.rpc.login.loginRemote.addOil(session, uid, session.frontendId, -cost, consts.OIL_ADD_TYPE.PURCHASE_MACHINE,'', function (err, errMsg) {
                        next(null, {
                            code: self.consts.Code.SUC,
                            msg: self.consts.Msg.RESULT_SUCCESS,
                            data: body.data
                        });
                        return;
                    });
                }
            }
        });
    }, function (err, ret) {
        //锁释放
        if (!!err) {
            console.error('c2sPurchaseMachine err 2:' + err)
        }
    })
}

/**
 * 试用矿机
 * @param msg
 * @param session
 * @param next
 */
handler.c2sInitMachine = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');
    var level = msg.level;

    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }

        self.httpRequest({
            url: 'http://39.98.74.164:9292/api/oil/machine/init?uid=' + uid + '&level=' + level + '&is_try=' + true,
            method: "GET"
        }, function (error, response, body) {
            if (response.statusCode != 200) {
                console.error('c2sInitMachine 执行失败 response.statusCOde' + response.statusCode)
                next(null, {
                    code: self.consts.Code.DATA_ERR,
                    msg: self.consts.Msg.NET_WORK_BUSY
                });
                return;
            } else {
                body = JSON.parse(body);
                if (body.code != '0') {
                    next(null, {
                        code: self.consts.Code.DATA_ERR,
                        msg: body.error
                    });
                    return;
                } else {
                    next(null, {
                        code: self.consts.Code.SUC,
                        msg: self.consts.Msg.RESULT_SUCCESS,
                        data: body.data
                    });
                    return;
                }
            }
        });
    });
}

/**
 * 获取石油产出明细
 * @param msg
 * @param session
 * @param next
 */
handler.c2sOilList = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');
    var pageNum = msg.page_num;
    var pageSize = msg.page_size;

    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }

        self.httpRequest({
            url: 'http://39.98.74.164:9292/api/oil/machine/list?uid=' + uid + '&page_num=' + pageNum + '&page_size=' + pageSize,
            method: "GET"
        }, function (error, response, body) {
            if (response.statusCode != 200) {
                console.error('c2sOilList 执行失败 response.statusCOde' + response.statusCode)
                next(null, {
                    code: self.consts.Code.DATA_ERR,
                    msg: self.consts.Msg.NET_WORK_BUSY
                });
                return;
            } else {
                body = JSON.parse(body);
                if (body.code != '0') {
                    next(null, {
                        code: self.consts.Code.DATA_ERR,
                        msg: body.error
                    });
                    return;
                } else {
                    next(null, {
                        code: self.consts.Code.SUC,
                        msg: self.consts.Msg.RESULT_SUCCESS,
                        data: body.data
                    });
                    return;
                }
            }
        });
    });
}

/**
 * 获取矿机收益记录
 * @param msg
 * @param session
 * @param next
 */
handler.c2sBalanceList = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');
    var pageNum = msg.page_num;
    var pageSize = msg.page_size;

    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }

        self.httpRequest({
            url: 'http://39.98.74.164:9292/api/oil/machine/balance?uid=' + uid + '&page_num=' + pageNum + '&page_size=' + pageSize,
            method: "GET"
        }, function (error, response, body) {
            if (response.statusCode != 200) {
                console.error('c2sBalanceList 执行失败 response.statusCOde' + response.statusCode)
                next(null, {
                    code: self.consts.Code.DATA_ERR,
                    msg: self.consts.Msg.NET_WORK_BUSY
                });
                return;
            } else {
                body = JSON.parse(body);
                if (body.code != '0') {
                    next(null, {
                        code: self.consts.Code.DATA_ERR,
                        msg: body.error
                    });
                    return;
                } else {
                    next(null, {
                        code: self.consts.Code.SUC,
                        msg: self.consts.Msg.RESULT_SUCCESS,
                        data: body.data
                    });
                    return;
                }
            }
        });
    });
}

/**
 * 将收益划转至余额
 * @param msg
 * @param session
 * @param next
 */
handler.c2sMoveToBalance = function (msg, session, next) {
    let self = this;
    let uid = session.get('uid');
    let earningId = msg.earning_id;

    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }

        self.httpRequest({
            url: 'http://39.98.74.164:9292/api/oil/machine/move?uid=' + uid + '&earning_id=' + earningId,
            method: "GET"
        }, function (error, response, body) {
            if (response.statusCode != 200) {
                console.error('c2sMoveToBalance 执行失败 response.statusCode' + response.statusCode)
                next(null, {
                    code: self.consts.Code.DATA_ERR,
                    msg: body.error
                });
                return;
            } else {
                body = JSON.parse(body);
                if (body.code != '0') {
                    next(null, {
                        code: self.consts.Code.DATA_ERR,
                        msg: body.error
                    });
                    return;
                } else {
                    //推送
                    pushUtils.onMoneyAdd(self.app, body.data, uid, session.frontendId, function () {
                    });
                    next(null, {
                        code: self.consts.Code.SUC,
                        msg: self.consts.Msg.RESULT_SUCCESS
                    });
                    return;
                }
            }
        });
    });
}

/**
 * 领取今日石油产出
 * @param msg
 * @param session
 * @param next
 */
handler.c2sReceiveDailyOil = function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');

    self.app.rpc.login.loginRemote.getUser(session, uid, function (err, userInfo) {
        if (!userInfo) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.USER_NOT_FOUND
            });
            return;
        }
        if (userInfo.video_num < 30) {
            next(null, {
                code: self.consts.Code.ERR,
                msg: self.consts.Msg.VIDEO_NUM_INSUFFICIENT
            });
            return;
        }

        self.httpRequest({
            url: 'http://39.98.74.164:9292/api/oil/machine/send_oil?uid=' + uid,
            method: "GET"
        }, function (error, response, body) {
            if (response.statusCode != 200) {
                console.error('c2sReceiveDailyOil 执行失败 response.statusCOde' + response.statusCode)
                next(null, {
                    code: self.consts.Code.DATA_ERR,
                    msg: self.consts.Msg.NET_WORK_BUSY
                });
                return;
            } else {
                body = JSON.parse(body);
                if (body.code != '0') {
                    next(null, {
                        code: self.consts.Code.DATA_ERR,
                        msg: body.error
                    });
                    return;
                } else {
                    next(null, {
                        code: self.consts.Code.SUC,
                        msg: self.consts.Msg.RESULT_SUCCESS,
                        data: body.data
                    });
                    return;
                }
            }
        });
    });
}

